<template>
  <div class="app-container">
    <el-tabs class="tab-container"
             v-model="activeName"
             tab-position="left"
             type="border-card"
             @tab-click="profileTabClick">
      <el-tab-pane label="个人资料" name="1">
        <el-tabs class="info-tab" v-model="infoActive" tab-position="right" type="border-card">
          <!-- el-tab-pane label="基本信息" name="11" -->
            <el-form :model="form" label-width="100px" ref="form">
              <el-row class="mt20">
                <el-col :span="12" :offset="6">
                  <el-form-item label="用户名：">
                    <span>{{form.username}}</span>
                    <el-button type="primary"
                               size="small"
                               style="float: right"
                               icon="el-icon-circle-check"
                               @click="saveProfile">保 存</el-button>
                  </el-form-item>
                </el-col>
                <el-col :span="12" :offset="6">
                  <el-form-item label="证件照：">
                    <el-upload
                      ref="avatarUpload"
                      class="avatar-uploader"
                      :action="uploadUrl"
                      :show-file-list="false"
                      :headers="headers"
                      :on-success="handleAvatarSuccess"
                      :before-upload="beforeAvatarUpload">
                      <img v-if="form.avatar" :src="imgUrl" class="avatar">
                      <div v-else class="avatar-uploader-icon">{{name}}</div>
                    </el-upload>
                  </el-form-item>
                </el-col>
                <el-col :span="12" :offset="6">
                  <el-form-item label="姓名：">
                    <el-input v-model="form.nickname" placeholder="请输入姓名"/>
                  </el-form-item>
                </el-col>
                
                
                <el-col :span="12" :offset="6">
                  <el-form-item label="性别：">
                    <Select v-model="form.gender"
                            placeholder="请选择性别"
                            :options="sexOptions"/>
                  </el-form-item>
                </el-col>
                <el-col :span="12" :offset="6">
                  <el-form-item label="出生日期：">
                    <el-date-picker v-model="form.birthday"
                                    type="date"
                                    placeholder="请选择出生日期"
                                    format="yyyy-MM-dd"
                                    value-format="yyyy-MM-dd"/>
                  </el-form-item>
                </el-col>
                <el-col :span="12" :offset="6">
                  <el-form-item label="联系方式：">
                    <el-input v-model="form.phone" placeholder="请输入联系方式"/>
                  </el-form-item>
                </el-col>
                <!-- el-col :span="12" :offset="6">
                  <el-form-item label="民族：">
                    <el-input v-model="form.nation" placeholder="请输入民族"/>
                  </el-form-item>
                </el-col -->
                
                
                <el-col :span="12" :offset="6">
                  <el-form-item label="邮箱：">
                    <el-input v-model="form.email" placeholder="请输入邮箱"/>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          <!-- /el-tab-pane -->

        </el-tabs>
      </el-tab-pane>
      <el-tab-pane label="修改密码" name="2">
        <el-form :model="passwordForm" label-width="100px" ref="pwdForm" :rules="pwdRules">
          <el-row class="mt20">
            <el-col :span="10" :offset="7">
              <el-form-item label="旧密码：" prop="oldPassword">
                <el-input v-model="passwordForm.oldPassword"
                          clearable
                          show-password
                          type="password"
                          placeholder="请输入旧密码" />
              </el-form-item>
            </el-col>
            <el-col :span="10" :offset="7">
              <el-form-item label="新密码：" prop="newPassword">
                <el-input v-model="passwordForm.newPassword"
                          type="password"
                          clearable
                          show-password
                          placeholder="请输入新密码" />
              </el-form-item>
            </el-col>
            <el-col :span="10" :offset="7">
              <el-form-item label="确认密码：" prop="checkPassword">
                <el-input v-model="passwordForm.checkPassword"
                          type="password"
                          clearable
                          show-password
                          placeholder="请再次输入新密码" />
              </el-form-item>
            </el-col>
            <el-col :span="10" :offset="7">
              <el-form-item prop="checkCode">
                <span slot="label">
                  <el-tooltip content="不包含大小写字母I/i、L/l、O/o、Q/q，且不区分大小写；点击右侧验证码将会刷新验证码。">
                    <i class="el-icon-question" style="cursor: pointer"></i>
                  </el-tooltip>
                  验证码：
                </span>
                <el-input v-model="passwordForm.checkCode"
                          clearable
                          style="width: 260px"
                          placeholder="请输入验证码">
                </el-input>
                <random-check-code @click.native="randomCheckCode" :identify-code="checkCode" style="float: right" />
              </el-form-item>
            </el-col>
            <el-col :span="10" :offset="7">
              <el-form-item>
                <el-button type="primary"
                           size="small"
                           icon="el-icon-circle-check"
                           @click="updatePassword">保 存</el-button>
                <el-button type="default"
                           size="small"
                           icon="el-icon-circle-check"
                           @click="resetPasswordForm">重 置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="我的收藏" name="5"></el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
  import {mapGetters} from 'vuex'
  import {getToken} from "@/utils/auth"
  import {getUserProfile, updateUserProfile, updateUserPwd} from "@/api/system/user";
  import RandomCheckCode from '@/components/RandomCheckCode'

  export default {
    name: "Profile",
    components: {RandomCheckCode},
    data() {
      const newPwdValidate = (rule, value, callback) => {
        if (value === undefined) {
          callback(new Error('请输入新密码'));
        } else {
          if (this.passwordForm.newPassword !== '') {
            this.$refs.pwdForm.validateField('checkPassword');
          }
          callback();
        }
      };
      const checkPwdValidate = (rule, value, callback) => {
        if (value === undefined) callback(new Error('请再次输入密码'));
        else if (value !== this.passwordForm.newPassword) callback(new Error('两次输入密码不一致'));
        else callback();
      };
      const checkCodeValidate = (rule, value, callback) => {
        if (value) value = value.toLowerCase()
        const code = this.checkCode.toLowerCase()
        if (value === undefined) callback(new Error('请输入验证码'))
        else if (value !== code) callback(new Error('验证码输入错误'))
        else callback()
      }
      return {
        // 当前处于活跃状态的选项卡
        activeName: '1',
        // 个人资料下的活跃状态选项卡
        infoActive: '11',
        // 个人资料表单
        form: {},
        // 头像上传地址
        uploadUrl: process.env.VUE_APP_BASE_API + '/upload/avatar',
        // 上传的请求头
        headers: {
          Authorization: 'Bearer ' + getToken()
        },
        // 照片的url
        imgUrl: '',
        // 性别状态字典
        sexOptions: [],



        // 修改密码的表单
        passwordForm: {},
        // 修改密码表单校验
        pwdRules: {
          oldPassword: [
            {required: true, message: '旧密码不能为空', trigger: 'blur'}
          ],
          newPassword: [
            {required: true, validator: newPwdValidate, trigger: 'blur'}
          ],
          checkPassword: [
            {required: true, validator: checkPwdValidate, trigger: 'blur'}
          ],
          checkCode: [
            {required: true, validator: checkCodeValidate, trigger: 'blur'}
          ]
        },
        // 随机验证码
        checkCode: ''
      }
    },
    computed: {
      ...mapGetters([
        'name'
      ]),
    },
    created() {
      this.getProfile()
      // 性别下拉选项
      this.getDicts("sys_user_sex").then(response => {
        this.sexOptions = response.data
      })

  

    },
    methods: {
      /** 查询用户个人资料 */
      getProfile() {
        this.reset()
        getUserProfile().then(res => {
          this.form = res.data
          //this.imgUrl = process.env.VUE_APP_BASE_API + this.form.avatar
          this.imgUrl =  this.form.avatar
        })
      },
      /** 重置form表单 */
      reset() {
        this.form = {
          name: undefined,

          avatar: undefined,

          phone: undefined,
          gender: '1',
          birthday: undefined,

          nativePlace: undefined,

          email: undefined,

        }
        this.resetForm('form')
      },
      /** 随机产生验证码 */
      randomCheckCode() {
        const secret = 'ABCDEFGHJKMNPRSTUVWXYZabcdefghjkmnprstuvwxyz0123456789'
        const length = secret.length
        this.checkCode = ''
        this.passwordForm.checkCode = undefined
        for (let i = 0; i < 4; i++) {
          this.checkCode += secret.charAt(Math.floor(Math.random() * length))
        }
      },
      /** 重置修改密码表单 */
      resetPasswordForm() {
        this.passwordForm = {
          oldPassword: undefined,
          newPassword: undefined,
          checkPassword: undefined,
          checkCode: undefined
        }
        this.resetForm('pwdForm')
        this.randomCheckCode()
      },
      /** 个人中心左侧tab栏切换事件 */
      profileTabClick(tab) {
        switch (tab.name) {
          case '2':
            this.resetPasswordForm()
            break
          default:
            break
        }
      },
    
      /** 上传图片前的校验 */
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      /** 上传成功的回调 */
      handleAvatarSuccess(res, file) {
        this.$set(this.form, 'avatar', res.file.url)
        //this.imgUrl = process.env.VUE_APP_BASE_API + this.form.avatar
        this.imgUrl =  this.form.avatar
      },
      /** 保存个人资料 */
      saveProfile() {
        updateUserProfile(this.form).then(res => {
          this.msgSuccess('保存成功')
        })
      },
      /** 确认修改密码 */
      updatePassword() {
        this.$refs.pwdForm.validate(valid => {
          if (valid) {
            updateUserPwd(this.passwordForm).then(res => {
              this.msgSuccess('保存成功')
              this.resetPasswordForm()
            })
          }
        })
      }
    }
  };
</script>

<style scoped lang="scss">
  .app-container {
    height: calc(100vh - 86px);
  }

  .tab-container {
    height: 100%;
    box-shadow: none;

    ::v-deep .el-tabs__content {
      padding: 0 !important;
      height: 100%;
      overflow: auto;
    }

    ::v-deep .el-tabs__header {
      border-bottom: none !important;
    }
  }

  .info-tab {
    height: calc(100vh - 128px);
    border: none;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    width: 98px;
    height: 98px;
    line-height: 98px;
    text-align: center;
    border: 1px dashed #409EFF;
    background: #409eff;
    color: #ffffff;
    border-radius: 8px;
    overflow: hidden;
  }

  .avatar {
    width: 98px;
    height: 98px;
    display: block;
    border-radius: 8px;
    overflow: hidden;
  }
</style>
